import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})
let cancelArr = []
// 请求拦截
_axios.interceptors.request.use(
  // axios的取消功能
  config => {
    cancelArr = cancelArr.filter(item => {
      if (item.method === config.method && item.url === config.url) {
        item.cancel()
        return true
      }
    })
    config.cancelToken = new axios.CancelToken(cancel => {
      cancelArr.push({
        url: config.url,
        method: config.method,
        cancel: cancel
      })
    })
    // 请求拦截统一加入token
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截
_axios.interceptors.response.use(
  res => {
    // 统一错误处理
    if (res.data.success) {
      return res.data
    } else {
      Message.error(res.data.message)
      // 直接让后面api调用执行.catch中止.then执行
      return Promise.reject(res.data.message)
    }
  },
  error => {
    console.log([error])
    // 响应拦截401问题
    if (error.response && error.response.status === 401) {
      store.commit('user/logout')
      router.push('/login?/login?redirect=' + location.href.split('#')[1])
    }
    return Promise.reject(error)
  }
)
export default _axios
